from PyQt5.QtCore import Qt
from PyQt5.QtGui import QBrush
from PyQt5.QtWidgets import QListWidgetItem, QLineEdit, QWidget, QComboBox, QPushButton, QHBoxLayout, QSizePolicy


from business.business import Business
from business.work import RoleWork


class CustomQListWidgetItem(QListWidgetItem):
    def __init__(self, i):
        super().__init__()
        self.count = i
        self.business = Business()
        # 自定义item中的widget 用来显示自定义的内容
        self.color = QBrush(Qt.lightGray) if i % 2 else QBrush(Qt.white)
        self.widget = QWidget()
        self.setBackground(self.color)
        # 用来显示name
        self.text_content = QLineEdit()
        self.text_content.setText(self.business.text_dict[i].text)
        # self.text_content.setFixedWidth(500)
        # 用来显示avator(图像)
        # self.role_label = QLabel()
        self.role_comboBox = QComboBox()
        self.role_comboBox.addItems(self.business.role_config_model.keys())
        self.role_comboBox.setCurrentText(self.business.text_dict[i].role)
        self.role_comboBox.currentTextChanged.connect(self.set_role_combo_box_changed)
        self.button = QPushButton('play')
        # 设置图像源 和 图像大小
        # self.avatorLabel.setPixmap(QPixmap(img).scaled(50, 50))
        # 设置布局用来对nameLabel和avatorLabel进行布局
        self.hbox = QHBoxLayout()
        self.widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # self.text_content.setSizePolicy()
        self.hbox.addWidget(self.role_comboBox)
        self.hbox.addWidget(self.button)
        self.hbox.addWidget(self.text_content)
        # 设置widget的布局
        self.widget.setLayout(self.hbox)
        # 设置自定义的QListWidgetItem的sizeHint，不然无法显示
        self.setSizeHint(self.widget.sizeHint())
        self.button.clicked.connect(self.play_music)
        self.text_content.textChanged.connect(self.update_text)
        # 工作线程
        self.worker = RoleWork(self.count)
        self.worker.count_signal.connect(self.work_finish)
        self.worker.tts_error.connect(self.tts_error)

    def update_text(self):
        self.business.text_dict[self.count].text = self.text_content.text()

    def set_role_combo_box_changed(self):
        self.business.text_dict[self.count].role = self.role_comboBox.currentText()

    def work_finish(self):
        self.button.setEnabled(True)

    def play_music(self):
        self.setBackground(self.color)
        self.button.setEnabled(False)
        self.worker.start()

    def tts_error(self):
        self.setBackground(QBrush(Qt.red))
